<?php

namespace app\admin\controller\fssy;

use app\common\controller\Backend;
use think\Log;
use think\Db;
use Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\library\Auth;
use app\common\library\RequestContext;
use app\common\MyLibrary\Utils; // 引入工具类 application\admin\command\MyLibrary\Utils.php

/**
 * 特慢病管理管理
 *
 * @icon fa fa-circle-o
 */
class Specialdisease extends Backend
{

    /**
     * Specialdisease模型对象
     * @var \app\admin\model\fssy\Specialdisease
     */
    protected $model = null;


    // 登录人员信息
    protected $loginer = null;


    // 是否允许关联搜索，默认为 true
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fssy\Specialdisease;
        $this->view->assign("genderDataList", $this->model->getGenderDataList());
        $this->view->assign("residentOrEmployeedDataList", $this->model->getResidentOrEmployeedDataList());
        $this->view->assign("remarksDataList", $this->model->getRemarksDataList());
        $this->view->assign("categoryDataList", $this->model->getCategoryDataList());

        // 获取当前登录人员信息
        $this->loginer = Utils::getLonginInfo($this->auth->getUserInfo(), $this->auth->getGroups());
        // Log::record('loginer = ' . json_encode($this->loginer));
    }

    /**
     * 索引页面处理方法
     *
     * 本方法主要用于处理索引页面的请求，包括Ajax请求和非Ajax请求
     * 当请求为Ajax时，根据请求参数决定是否跳转到Selectpage处理逻辑，
     * 否则根据请求参数构建查询条件，对数据进行分页查询，并返回查询结果
     */
    public function index()
    {
        // 指定搜索字段，这里为“管理员用户名”和“日志ID”
        // $this->searchFields = ["gender_data"];

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //判断请求是否为Ajax，若不是则直接返回视图
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        //解析请求参数，构建查询条件、排序规则及分页参数
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        //执行查询，根据构建的查询条件、排序规则及分页参数获取数据列表
        $list = $this->model
            ->with(["dictsregion", "dictsdiseaseidname", "dictsexpert1", "dictsexpert2"])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        //构建返回结果，包括总记录数和当前页记录列表
        $result = ['total' => $list->total(), 'rows' => $list->items()];

        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            // 往前端传数据
            $this->view->assign('operator', $this->loginer['userName']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();

            // 获取错误消息
            $errorMessage = $e->getMessage();
            // 检查 身份证号码重复 错误消息是否包含特定字符串
            if (strpos($errorMessage, 'Duplicate entry') !== false && strpos($errorMessage, 'id_number') !== false) {
                $resultError = "身份证号码重复，请重新输入.";
            } elseif (strpos($errorMessage, 'Duplicate entry') !== false && strpos($errorMessage, 'medical_card_number') !== false) {
                $resultError = "医保卡号码重复，请重新输入.";
            } else {
                $resultError = $errorMessage;
            }
            // $this->error($e->getMessage());
            $this->error($resultError);
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('operator', $this->loginer['userName']);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();

            // 获取错误消息
            $errorMessage = $e->getMessage();
            // 检查 身份证号码重复 错误消息是否包含特定字符串
            if (strpos($errorMessage, 'Duplicate entry') !== false && strpos($errorMessage, 'id_number') !== false) {
                $resultError = "身份证号码重复，请重新输入.";
            } elseif (strpos($errorMessage, 'Duplicate entry') !== false && strpos($errorMessage, 'medical_card_number') !== false) {
                $resultError = "医保卡号码重复，请重新输入.";
            } else {
                $resultError = $errorMessage;
            }
            // $this->error($e->getMessage());
            $this->error($resultError);
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    // 得到当前用户的名
    public function currentUser()
    {
        // $authVal = $this->auth->id;
        // return json(['authVal' => $authVal]);
        // // 获取当前登录的用户信息
        $user = $this->auth->username; //获取用户名
        return json(['user' => $user]);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
